const router = require('koa-router')()
const fs = require("fs")
const path = require("path")

router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})

router.post('/uploadfile',async (ctx,next) => {
  //上传单个文件
  const file = ctx.request.files.file;
  //创建可读流
  const reader = fs.createReadStream(file.path);
  let filePath = path.join(__dirname,'/') + `/${file.name}`;
  //创建可写流
  const upStream = fs.createWriteStream(filePath);
  //可读流通过管道写入可写流
  reader.pipe(upStream);
  return ctx.body = '上传成功！';
});

module.exports = router
